package com.hhhn.wk.widget.picture_viewer;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.TextView;


import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.utils.StatusBarUtil;

import java.util.ArrayList;

/**
 * 图片查看器
 */
public class ImagePagerActivity extends BaseActivity {
    private static final String STATE_POSITION = "STATE_POSITION";
    public static final String EXTRA_IMAGE_INDEX = "image_index";
    public static final String EXTRA_IMAGE_URLS = "image_urls";
    private HackyViewPager mPager;
    private int pagerPosition;
    private TextView indicator;
    private View mViewNeedOffset;

    String urlFragment="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
        ArrayList<String> urls = getIntent().getStringArrayListExtra(EXTRA_IMAGE_URLS);
        mViewNeedOffset=findViewById(R.id.view_need_offset);
        mPager = (HackyViewPager) findViewById(R.id.pager);
        ImagePagerAdapter mAdapter = new ImagePagerAdapter(getSupportFragmentManager(),urls);
        mPager.setAdapter(mAdapter);
        indicator = (TextView) findViewById(R.id.indicator);
        CharSequence text = getString(R.string.viewpager_indicator, 1, mPager.getAdapter().getCount());
        indicator.setText(text);
        if (savedInstanceState != null) {
            pagerPosition = savedInstanceState.getInt(STATE_POSITION);
        }
// 更新下标
        mPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int arg0) {
                CharSequence text = getString(R.string.viewpager_indicator, arg0 + 1, mPager.getAdapter().getCount());
                indicator.setText(text);
            }

        });

        mPager.setCurrentItem(pagerPosition);
//		btn_save.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//
//				if(mImageView.getDrawable() instanceof BitmapDrawable){
////                    Toast.makeText(myContext,"长按保存图片至相册",Toast.LENGTH_SHORT).show();
//					File fileDir=new File(getApplication().getExternalCacheDir(),"images");
//					File file=new File(fileDir.getAbsolutePath()+"/"+urlFragment+".png");
//					if(file!=null&&file.length()>0){
//						CameraRollManager rollManager=new CameraRollManager(ImagePagerActivity.this, Uri.parse(file.getAbsolutePath()));
//						rollManager.execute();
//					}
//				}
//			}
//		});
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//			if (ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
//					!= PackageManager.PERMISSION_GRANTED) {
//				requestAlertWindowPermission();//权限问题
//			}
//		}
//		loadImage();//
    }

    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.picyure_viewer_image_pager);
        StatusBarUtil.setTransparentForImageViewInFragment(ImagePagerActivity.this, null);
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initClick() {

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_POSITION, mPager.getCurrentItem());
    }

    private class ImagePagerAdapter extends FragmentStatePagerAdapter {
        public ArrayList<String> fileList;
        public ImagePagerAdapter(FragmentManager fm, ArrayList<String> fileList) {
            super(fm);
            this.fileList = fileList;
        }
        @Override
        public int getCount() {
            return fileList == null ? 0 : fileList.size();
        }

        @Override
        public Fragment getItem(int position) {
            urlFragment = fileList.get(position);

            return ImageDetailFragment.newInstance(urlFragment);
        }
    }

//	@Override
//	protected void setStatusBar() {
//		mViewNeedOffset = findViewById(R.id.view_need_offset);
//		StatusBarUtil.setTransparentForImageView(ImagePagerActivity.this, mViewNeedOffset);
//	}

//
//	private static final int REQUEST_CODE = 1;
//	private  void requestAlertWindowPermission() {
//		ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE);
//	}
//
//	private void loadImage() {
//		DownImageTask task = new DownImageTask(mImageView);
//		task.execute(IMAGE_URL);
//	}
//
//	private class DownImageTask extends AsyncTask<String, Long, Bitmap> {
//		private ImageView imageView;
//		private long contentLength;
//		public DownImageTask(ImageView imageView) {
//			this.imageView = imageView;
//		}
//
//		@Override
//		protected Bitmap doInBackground(String... params) {
//			Bitmap bitmap = null;
//			BufferedInputStream bis = null;
//			ByteArrayOutputStream bos = null;
//			try {
////                File fileDir=new File(getApplication().getExternalCacheDir(),"images");
////                if(fileDir==null||!fileDir.isDirectory()){
////                    fileDir.mkdir();
////                }
////                File file=new File(fileDir.getAbsolutePath()+"/"+params[0].hashCode()+".png");
////                if(file!=null&&file.length()>0){
////                    return bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
////                }
//				bos=new ByteArrayOutputStream();
//				byte[] buffer = new byte[512];
//				long total=0;
//				int len ;
//				URL url = new URL(params[0]);
//				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//				this.contentLength = conn.getContentLength();
//				bis = new BufferedInputStream(conn.getInputStream());
//				while ((len = bis.read(buffer)) != -1) {
//					SystemClock.sleep(200);
//					total+=len;
//					publishProgress(total);
//					bos.write(buffer, 0, len);
//					bos.flush();
//				}
//				bitmap= BitmapFactory.decodeByteArray(bos.toByteArray(),0,bos.toByteArray().length);
//				saveBitmapToDisk(bos,params[0]);
//			} catch (Exception e) {
//				e.printStackTrace();
//			} finally {
//				try {
//					if (bis != null) {
//						bis.close();
//					}
//					if (bos != null) {
//						bos.close();
//					}
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//			return bitmap;
//		}
//
//		private void saveBitmapToDisk(final ByteArrayOutputStream baos, final String url) {
//			new Thread(){
//				@Override
//				public void run() {BufferedOutputStream bos=null;
//					try{
//						if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
//							Log.e("TAG","内存卡不存在");
//							return;
//						}
//						Log.e("TAG","开始保存图片至内存卡～～");
//						byte[] bytes = baos.toByteArray();
//						File fileDir=new File(getApplication().getExternalCacheDir(),"images");
//						if(fileDir==null||!fileDir.isDirectory()){
//							fileDir.mkdir();
//						}
//						File file=new File(fileDir.getAbsolutePath()+"/"+url.hashCode()+".png");
//						file.createNewFile();
//						bos=new BufferedOutputStream(new FileOutputStream(file));
//						bos.write(bytes);
//						bos.flush();
//						Log.e("TAG","图片已经保存至内存卡～～");
//					}catch (Exception e){
//						e.printStackTrace();
//					}finally {
//						if(bos!=null){
//							try {
//								bos.close();
//							} catch (IOException e) {
//								e.printStackTrace();
//							}
//						}
//					}
//				}
//			}.start();
//		}
//
//		@Override
//		protected void onProgressUpdate(Long... values) {
////			mLoadingView.setProgress(((values[0].longValue() * 1.0f / contentLength)));
//		}
//
//		@Override
//		protected void onPostExecute(Bitmap bitmap) {
//			if (imageView != null && bitmap != null) {
//				imageView.setImageBitmap(bitmap);
////				mLoadingView.loadComplete();
//			}
//		}
//	}
//	@Override
//	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//		if (requestCode == REQUEST_CODE) {
//			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//				if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//						== PackageManager.PERMISSION_GRANTED) {
//					return;
//				}
//			}
//		}
//	}




}
